package com.kaifamiao.controller;

import com.kaifamiao.entity.FileInfo;
import com.kaifamiao.entity.User;
import com.kaifamiao.exception.ServiceException;
import com.kaifamiao.service.FileService;
import com.kaifamiao.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private FileService fileService;
    @Autowired
    private UserService userService;

    @PostMapping("/upload")
    public Map<String, Object> upload(@RequestPart("upfile") MultipartFile mf, @RequestAttribute("userId") Integer userId) {
        // 获得原始文件名称
        String original = mf.getOriginalFilename();
        byte[] bytes;
        try {
            bytes = mf.getBytes();
        } catch ( IOException e ) {
            log.error( "读取文件内容失败" , e);
            return Map.of("success", false, "message", "上传失败", "reason", e.getMessage() );
        }

        FileInfo fi = new FileInfo();
        fi.setName( original ); // 设置文件原始名称
        fi.setContent( bytes ); // 设置文件内容(即字节数据)
        User user = userService.find(userId); // 获得当前已登录用户
        fi.setUploader( user ); // 设置文件上传者(以当前登录用户为上传者)

        try {
            if( fileService.save(fi) ) {
                return Map.of("success", true, "message", "上传成功");
            }
            return Map.of("success", false, "message", "上传失败");
        } catch ( ServiceException e ) {
            log.error( "保存文件信息及其内容时发生错误" , e);
            return Map.of("success", false, "message", "上传失败", "reason", e.getMessage() );
        }

    }

    @GetMapping("/mine")
    public Map<String, Object> myFiles(@RequestAttribute("userId") Integer userId) {
        try {
            List<FileInfo> list = fileService.loadFiles(userId, false);
            return Map.of("success", true, "message", "查询成功", "result", list);
        } catch ( ServiceException e ) {
            log.error("查询失败",e);
            return Map.of("success", true, "message", "查询失败", "reason", e.getMessage());
        }
    }

    @GetMapping("/other")
    public Map<String, Object> otherFiles(@RequestAttribute("userId") Integer userId) {
        try {
            List<FileInfo> list = fileService.loadFiles(userId, true);
            return Map.of("success", true, "message", "查询成功", "result", list);
        } catch ( ServiceException e ) {
            log.error("查询失败",e);
            return Map.of("success", true, "message", "查询失败", "reason", e.getMessage());
        }
    }
}
